package net.zjitc.service.Impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import net.zjitc.Utils.CommonUtils;
import net.zjitc.Utils.MailUtils;
import net.zjitc.dao.AdminDao;
import net.zjitc.pojo.AdminUser;
import net.zjitc.pojo.User;
import net.zjitc.redis.Redis;
import net.zjitc.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/23 15:15
 * @description:
 */
@Service
public class AdminServiceImpl implements AdminService {
  @Autowired
  private AdminDao adminDao;

  @Autowired
  private  Jedis jedis;

  @Autowired
  private Redis redis;

  @Override
  public AdminUser AdminLogin(String username, String password) {
    return adminDao.AdminLogin(username,password);
  }
  @Override
  public List<User> findAllUser() {
    String string = jedis.get("user");
    Gson gson =new Gson();
    List<User> userList =gson.fromJson(string,new TypeToken<List<User>>(){}.getType());
    return userList;
  }

  @Override
  public User findByCondition(String username, String password) {
    String string =jedis.get("user");
    Gson gson =new Gson();
    List<User> userList =gson.fromJson(string,new TypeToken<List<User>>(){}.getType());
    for (User u:userList){
      if (u.getUsername().equals(username) && u.getPassword().equals(password)){
        return u;
      }
    }
    return null;
  }

  @Override
  public Integer DeleteUser(Integer uid) {
    //从数据库中删除所选的字段
    adminDao.DeleteUser(uid);
    Gson gson =new Gson();
    //更新Redis中的缓存数据
    List<User> userList = adminDao.findAllUser();
    String UserList = gson.toJson(userList);
    redis.set("user", UserList);
    return null;
  }

  @Override
  public Integer insert(User user) {
    //设置状态码  1表示激活  0表示末激活
    user.setState(0);
    String code = CommonUtils.uuid()+CommonUtils.uuid();
    user.setCode(code);
    try {
      //发送邮件
      MailUtils.sendMail(user.getEmail(),code);
    } catch (Exception e) {
      e.printStackTrace();
    }
    adminDao.insert(user);
    Gson gson =new Gson();
    List<User> userList = adminDao.findAllUser();
    String UserList = gson.toJson(userList);
    redis.set("user", UserList);
    return null;
  }

  @Override
  public Integer findByCode(String code) {
    adminDao.findBYCOde(code);
    return null;
  }

}